package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;

import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisIdWorker;

import com.hmdp.utils.UserHolder;

import org.redisson.api.RedissonClient;

import org.springframework.core.io.ClassPathResource;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {


    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static DefaultRedisScript<Long> redisScript;

    static {
        redisScript = new DefaultRedisScript<Long>();
        redisScript.setLocation(new ClassPathResource("seckill.lua"));
        redisScript.setResultType(Long.class);
    }


    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                redisScript, Collections.emptyList(), voucherId.toString(), userId.toString()
        );
        //2.判断返回值是否为0
        //2.1返回值不为0
        if (result != 0) {
            return Result.fail( result ==1 ? "库存不足！":"请勿重复下单");
        }
        //2.2返回值为0
        long orderId = redisIdWorker.generateId(RedisConstants.SECKILL_ORDER_KEY);
        //有购买资格，把下单信息保存至阻塞队列
        //TODO

        return Result.ok(orderId);
    }


    @Transactional
    @Override
    public Result creatVoucherOrder(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        int count = count(new LambdaQueryWrapper<VoucherOrder>().eq(VoucherOrder::getUserId, userId).eq(VoucherOrder::getVoucherId,voucherId));
        if (count > 0) {
            return Result.fail("请勿重复下单");
        }
        //5.优惠券的数量减一，并更新到数据库
        seckillVoucherService.update().setSql("stock = stock -1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();
        //6.生成订单，存入订单表
        VoucherOrder order = createOrder(voucherId);
        this.save(order);
        //7.返回订单编号
        return Result.ok(order.getId());
    }


    /**
     * 创建对应优惠券的订单
     */
    public VoucherOrder createOrder(Long voucherId) {
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.generateId(RedisConstants.SECKILL_ORDER_KEY));
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setPayType(2);
        voucherOrder.setStatus(2);
        return voucherOrder;
    }
}
